package redisinit

import (
	"context"
	"fmt"
	"meituan_srv/meituan"
	"strconv"
)

func CartAdd(Cover, Name, Status string, Num, UserId, MeiTuanId int64, Price float64) error {
	key := fmt.Sprintf("cart:user_id_%d:mei_tuan_id_%d", UserId, MeiTuanId)
	return Rdb.HMSet(context.Background(), key, map[string]interface{}{
		"Cover":     Cover,
		"Name":      Name,
		"Status":    Status,
		"Num":       Num,
		"UserId":    UserId,
		"MeiTuanId": MeiTuanId,
		"Price":     Price,
		"Checked":   1,
	}).Err()
}
func RemoveCart(UserId, MeiTuanId int64) error {
	key := fmt.Sprintf("cart:user_id_%d:mei_tuan_id_%d", UserId, MeiTuanId)
	return Rdb.Del(context.Background(), key).Err()
}
func UpdateCartNum(UserId, MeiTuanId, Num int64) error {
	key := fmt.Sprintf("cart:user_id_%d:mei_tuan_id_%d", UserId, MeiTuanId)
	return Rdb.HSet(context.Background(), key, "Num", Num).Err()
}
func ListCart(UserId int64) (lists []*meituan.CartList, err error) {
	key := fmt.Sprintf("cart:user_id_%d:mei_tuan_id_*", UserId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		listss := Rdb.HGetAll(context.Background(), s).Val()
		Cover := listss["Cover"]
		Name := listss["Name"]
		Status := listss["Status"]
		Num, _ := strconv.Atoi(listss["Num"])
		Price, _ := strconv.ParseFloat(listss["Price"], 64)
		lists = append(lists, &meituan.CartList{
			Cover:  Cover,
			Name:   Name,
			Status: Status,
			Num:    int64(Num),
			Price:  float32(Price),
		})
	}
	return
}
func CartCount(UserId int64) (count int, sum float64, err error) {
	key := fmt.Sprintf("cart:user_id_%d:mei_tuan_id_*", UserId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		listss := Rdb.HGetAll(context.Background(), s).Val()
		num, _ := strconv.Atoi(listss["Num"])
		price, _ := strconv.ParseFloat(listss["Price"], 64)
		count += num
		sum += price * float64(count)
	}
	return
}
func DeleteCart(UserId int64) {
	key := fmt.Sprintf("cart:user_id_%d:mei_tuan_id_*", UserId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		Rdb.Del(context.Background(), s).Err()
	}
}
